<template>
  <div class="Discretebox">
    <div class="topbox">
      <el-form ref="form" label-position="left" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="光伏系统">
              <FilterSelect2
                v-model="companyId"
                :optionlist="xitonglist"
                @updateModelValue="changexitong"
                :valuekey="{ name: 'name', value: 'id' }"
              ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="19" style="text-align: right">
            <el-form-item label="">
              <el-button size="small" @click="chongzhi">重 置</el-button>
              <el-button size="small" type="primary" @click="gettablelist"
                >查 询</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="bodybox">
      <div class="title">
        <div>离散分析</div>
        <div>
          <TopTile
            @command="command"
            @daochu="daochu"
            @shuaxin="shuaxin"
          ></TopTile>
        </div>
      </div>
      <div class="echandtab">
        <div class="chart-section">
          <div class="chart-container">
            <nt-echart
              :loading="chartLoading"
              :options="chartOptions"
            ></nt-echart>
          </div>
          <div class="legend-section">
            <div class="legend-table">
              <div class="legend-header">
                <div class="legend-header-cell"></div>
                <div class="legend-header-cell">数量(台)</div>
                <div class="legend-header-cell">占比</div>
              </div>
              <div
                class="legend-row"
                v-for="item in legendData"
                :key="item.type"
              >
                <div class="legend-status-cell">
                  <span class="legend-status-text">{{ item.type }}</span>
                  <span
                    class="legend-color"
                    :style="{ backgroundColor: getStatusColor(item.type) }"
                  ></span>
                </div>
                <div class="legend-cell">{{ item.count }}</div>
                <div class="legend-cell">{{ item.percentage }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="status-legend">
          <div class="status-legend-item">
            <span class="status-color" style="background-color: #0088cf"></span>
            <span class="status-text">运行优秀: 离散率为0-5%</span>
          </div>
          <div class="status-legend-item">
            <span class="status-color" style="background-color: #7bbffe"></span>
            <span class="status-text">运行良好: 离散率为5%-10%</span>
          </div>
          <div class="status-legend-item">
            <span class="status-color" style="background-color: #5dd696"></span>
            <span class="status-text">个别偏低: 离散率为10%-20%</span>
          </div>
          <div class="status-legend-item">
            <span class="status-color" style="background-color: #ffa500"></span>
            <span class="status-text"
              >有待提高: 离散率为>20%或者组串电流为0</span
            >
          </div>
        </div>
        <div class="table-section">
          <el-table
            ref="tabledata"
            :data="tableData"
            :size="issize"
            border
            v-loading="loading"
            max-height="calc(100% - 1px)"
            style="width: 100%"
            :header-cell-style="{
              'text-align': 'center',
              background: '#f5f5f5'
            }"
          >
            <el-table-column
              type="index"
              label="序号"
              width="70"
              align="center"
            />
            <el-table-column prop="stationName" label="光伏电站" />
            <el-table-column prop="inverterName" label="逆变器" />
            <el-table-column prop="maxCurrent" label="最大电流" align="right" />
            <el-table-column prop="minCurrent" label="最小电流" align="right" />
            <el-table-column prop="discreteRate" label="离散率" align="right" />
            <el-table-column label="操作" width="120" align="center">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="handleDetail(scope.row)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
      :visible.sync="detailVisible"
      title="逆变器电流详情"
      width="600px"
      :before-close="() => (detailVisible = false)"
      custom-class="detail-dialog"
    >
      <div
        v-if="
          detailData.inverterVoltageList &&
          detailData.inverterVoltageList.length > 0
        "
      >
        <div class="mt-20">
          <h4>电流详细信息：</h4>
          <el-table
            max-height="400px"
            :data="detailData.inverterVoltageList"
            border
          >
            <el-table-column prop="name" label="电流名称" />
            <el-table-column
              prop="value"
              label="电流值(A)"
              :formatter="(row) => `${row.value} A`"
            />
          </el-table>
        </div>
      </div>
      <div v-else class="text-center py-40">
        <div>暂无详细信息</div>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import TopTile from '@/components/TopTitle/index.vue'
import ntEchart from '@/components/nt-echart.vue'
import { exportexcel } from '@/utils/excel'
import { getphotovollistapi } from '@/api/Photovoltaic/analysis/YoyAnalysis'
import {
  getDiscreteAnalysisListApi,
  exportDiscreteAnalysisApi
} from '@/api/Photovoltaic/analysis/Discrete'

export default {
  name: 'DiscreteAnalysis',
  components: {
    TopTile,
    ntEchart
  },
  data() {
    return {
      loading: false,
      chartLoading: false,
      issize: 'medium',
      companyId: '',
      xitonglist: [],
      tableData: [],
      detailVisible: false,
      detailData: {},
      legendData: [],
      chartOptions: {}
    }
  },

  async mounted() {
    const {
      data: { list }
    } = await getphotovollistapi()
    this.xitonglist = list
    const PhotoCompanyId = localStorage.getItem('PhotoCompanyId')
    this.$set(this, 'companyId', PhotoCompanyId ? +PhotoCompanyId : list[0].id)
    this.gettablelist()
  },

  methods: {
    async gettablelist() {
      this.loading = true
      try {
        const res = await getDiscreteAnalysisListApi({
          classId: this.companyId
        })
        if (res.data && res.data.list) {
          this.tableData = res.data.list.map((item) => ({
            ...item,
            maxCurrent:
              item.maxCurrent !== null && item.maxCurrent !== undefined
                ? `${item.maxCurrent} A`
                : '-',
            minCurrent:
              item.minCurrent !== null && item.minCurrent !== undefined
                ? `${item.minCurrent} A`
                : '-',
            discreteRate:
              item.discreteRate !== null && item.discreteRate !== undefined
                ? `${item.discreteRate}%`
                : '-'
          }))
        } else {
          this.tableData = []
        }
      } catch (error) {
        console.error('获取离散分析数据失败:', error)
        this.tableData = []
      } finally {
        this.loading = false
      }
      this.getfadianlv()
    },

    // 系统下拉存本地
    changexitong(val) {
      localStorage.setItem('PhotoCompanyId', val)
    },

    // 获取状态颜色
    getStatusColor(type) {
      const colorMap = {
        运行优秀: '#0088cf',
        运行良好: '#7bbffe',
        个别偏低: '#5dd696',
        有待提高: '#ffa500'
      }
      return colorMap[type] || '#ccc'
    },

    // 获取离散分析图
    async getfadianlv() {
      this.chartLoading = true
      try {
        const {
          data: { content }
        } = await getDiscreteAnalysisListApi({
          classId: this.companyId
        })

        // 解析content字段中的JSON数据
        let chartData = []
        try {
          chartData = JSON.parse(content)
        } catch (error) {
          console.error('解析图表数据失败:', error)
          chartData = []
        }

        // 确保有所有状态类型的数据
        const defaultStatuses = [
          { type: '运行优秀', count: 0 },
          { type: '运行良好', count: 0 },
          { type: '个别偏低', count: 0 },
          { type: '有待提高', count: 0 }
        ]

        // 合并API数据和默认数据
        const mergedData = defaultStatuses.map((defaultItem) => {
          const apiItem = chartData.find(
            (item) => item.type === defaultItem.type
          )
          return apiItem || defaultItem
        })

        // 计算总数和百分比
        const total = mergedData.reduce(
          (sum, item) => sum + (item.count || 0),
          0
        )

        // 为每个数据项添加百分比
        const dataWithPercentage = mergedData.map((item) => ({
          ...item,
          percentage:
            total > 0
              ? (((item.count || 0) / total) * 100).toFixed(2) + '%'
              : '0.00%'
        }))

        // 更新图例数据
        this.legendData = dataWithPercentage

        // 定义颜色映射
        const colorMap = {
          运行优秀: '#0088cf', // 蓝色
          运行良好: '#7bbffe', // 浅蓝色
          个别偏低: '#5dd696', // 绿色
          有待提高: '#ffa500' // 橙色
        }

        const seriesData = mergedData.map((item) => ({
          name: item.type,
          value: item.count,
          itemStyle: {
            color: colorMap[item.type] || '#ccc'
          }
        }))

        this.chartOptions = {
          backgroundColor: '#fff',
          tooltip: {
            trigger: 'item',
            formatter: function (params) {
              const data = dataWithPercentage.find(
                (item) => item.type === params.name
              )
              return `${params.name}<br/>数量: ${params.value}台<br/>占比: ${
                data ? data.percentage : '0.00%'
              }`
            }
          },
          legend: {
            show: false
          },
          series: [
            {
              name: '运行状态分布',
              type: 'pie',
              radius: ['35%', '70%'],
              center: ['50%', '50%'],
              avoidLabelOverlap: false,
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: false
                }
              },
              labelLine: {
                show: false
              },
              data: seriesData
            }
          ]
        }
      } catch (error) {
        console.error('获取离散分析图表数据失败:', error)
      } finally {
        this.chartLoading = false
      }
    },

    // 详情处理
    handleDetail(row) {
      this.detailData = row
      this.detailVisible = true
    },

    // 重置
    chongzhi() {
      const PhotoCompanyId = localStorage.getItem('PhotoCompanyId')
      this.$set(
        this,
        'companyId',
        PhotoCompanyId ? +PhotoCompanyId : this.xitonglist[0].id
      )
      this.gettablelist()
    },

    // 调节表格密度
    command(val) {
      if (val === '默认') {
        this.issize = 'medium'
      } else if (val === '中等') {
        this.issize = 'small'
      } else {
        this.issize = 'mini'
      }
    },

    // 导出
    daochu() {
      exportexcel(
        'pes-microservice-biz/pes/discrete/analysis/export',
        { classId: this.companyId },
        '离散分析'
      )
    },

    // 刷新列表
    shuaxin() {
      this.gettablelist()
      this.$message.success('列表刷新成功')
    }
  }
}
</script>
<style lang="scss" scoped>
.Discretebox {
  height: 100%;
  padding: 10px;
  .topbox {
    height: 80px;
    background-color: #fff;
    padding: 20px;
    margin-bottom: 10px;
  }
  .bodybox {
    height: calc(100% - 90px);
    background-color: #fff;
    padding: 20px;
    .title {
      margin-bottom: 10px;
      display: flex;
      justify-content: space-between;
    }
    .echandtab {
      height: 95%;
      .chart-section {
        height: 50%;
        display: flex;
        gap: 20px;
        margin-bottom: 20px;

        .chart-container {
          flex: 1;
          height: 100%;
          padding: 0;

          :deep(.charts) {
            width: 100%;
            height: 100%;
          }
        }

        .legend-section {
          width: 500px;
          margin-bottom: 0;
          align-self: flex-start;
        }
      }

      .status-legend {
        margin-bottom: 20px;
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
        align-items: center;

        .status-legend-item {
          display: flex;
          align-items: center;
          gap: 8px;

          .status-color {
            width: 16px;
            height: 16px;
            border-radius: 2px;
            display: inline-block;
          }

          .status-text {
            font-size: 12px;
            color: #666;
          }
        }
      }

      .table-section {
        height: 40%;
      }
    }
  }
}

.legend-section {
  margin-bottom: 20px;
  padding: 20px;

  .legend-table {
    display: table;
    width: 100%;
    border-collapse: collapse;

    .legend-header {
      display: table-row;

      .legend-header-cell {
        display: table-cell;
        font-size: 14px;
        font-weight: 600;
        color: #333;
        text-align: center;
        border: none;
      }
    }

    .legend-row {
      display: table-row;

      .legend-status-cell {
        display: table-cell;
        padding: 10px 12px;
        font-size: 14px;
        color: #333;
        text-align: left;
        border: none;
        vertical-align: middle;
        white-space: nowrap;

        .legend-color {
          width: 25px;
          height: 14px;
          border-radius: 2px;
          display: inline-block;
          margin-left: 8px;
          vertical-align: middle;
        }

        .legend-status-text {
          vertical-align: middle;
        }
      }

      .legend-cell {
        display: table-cell;
        padding: 10px 12px;
        font-size: 14px;
        color: #333;
        text-align: center;
        border: none;
        vertical-align: middle;
      }
    }
  }
}

// 详情对话框样式
:deep(.detail-dialog) {
  .el-dialog__body {
    padding: 20px;
  }
}
</style>
